<template>
  <div class="add-vuln-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加漏洞</span>
        </div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="CVE编号" prop="cve_id">
          <el-input v-model="form.cve_id" placeholder="请输入CVE编号"></el-input>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-select v-model="form.severity" placeholder="请选择严重程度">
            <el-option label="严重" value="critical"></el-option>
            <el-option label="高危" value="high"></el-option>
            <el-option label="中危" value="medium"></el-option>
            <el-option label="低危" value="low"></el-option>
            <el-option label="信息" value="info"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="新发现" value="new"></el-option>
            <el-option label="已验证" value="verified"></el-option>
            <el-option label="修复中" value="in_progress"></el-option>
            <el-option label="已修复" value="fixed"></el-option>
            <el-option label="已关闭" value="closed"></el-option>
            <el-option label="误报" value="false_positive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="漏洞类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择漏洞类型">
            <el-option label="SQL注入" value="sql_injection"></el-option>
            <el-option label="跨站脚本" value="xss"></el-option>
            <el-option label="命令注入" value="cmd_injection"></el-option>
            <el-option label="服务器端请求伪造" value="ssrf"></el-option>
            <el-option label="文件上传" value="file_upload"></el-option>
            <el-option label="文件包含" value="file_inclusion"></el-option>
            <el-option label="信息泄露" value="info_disclosure"></el-option>
            <el-option label="未授权访问" value="unauthorized_access"></el-option>
            <el-option label="弱密码" value="weak_password"></el-option>
            <el-option label="错误配置" value="misconfiguration"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联资产" prop="assets">
          <el-select v-model="form.assets" multiple placeholder="请选择关联资产" :loading="loadingAssets">
            <el-option
              v-for="asset in assetList"
              :key="asset.id"
              :label="asset.name"
              :value="asset.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入漏洞描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="重现步骤" prop="reproduce_steps">
          <el-input
            v-model="form.reproduce_steps"
            type="textarea"
            :rows="4"
            placeholder="请输入重现步骤"
          ></el-input>
        </el-form-item>
        <el-form-item label="解决方案" prop="solution">
          <el-input
            v-model="form.solution"
            type="textarea"
            :rows="3"
            placeholder="请输入解决方案"
          ></el-input>
        </el-form-item>
        <el-form-item label="参考链接" prop="references">
          <el-input
            v-model="form.references"
            type="textarea"
            :rows="2"
            placeholder="请输入参考链接，多个链接可使用换行分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="CVSS评分" prop="cvss">
          <el-slider v-model="form.cvss" :min="0" :max="10" :step="0.1"></el-slider>
          <div class="cvss-value">{{ form.cvss.toFixed(1) }}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createVulnerability } from '@/api/vulnerability'
import { getAllAssets } from '@/api/asset'

export default {
  name: 'AddVulnerability',
  setup() {
    const formRef = ref(null)
    const saving = ref(false)
    const router = useRouter()
    const assetList = ref([])
    const loadingAssets = ref(false)
    
    const form = reactive({
      title: '',
      cve_id: '',
      severity: '',
      status: 'new',
      type: 'other',
      description: '',
      reproduce_steps: '',
      solution: '',
      references: '',
      cvss: 0,
      assets: []
    })
    
    const rules = reactive({
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      severity: [{ required: true, message: '请选择严重程度', trigger: 'change' }],
      type: [{ required: true, message: '请选择漏洞类型', trigger: 'change' }],
      description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
    })
    
    const handleSubmit = async () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          saving.value = true
          try {
            // 确保发送的数据格式与后端期望的一致
            const formData = {
              title: form.title,
              cve_id: form.cve_id,
              severity: form.severity,
              status: form.status,
              type: form.type,
              description: form.description,
              reproduce_steps: form.reproduce_steps,
              solution: form.solution,
              references: form.references,
              cvss: form.cvss,
              // 确保assets是ID数组而不是对象数组
              assets: Array.isArray(form.assets) 
                ? form.assets.map(asset => typeof asset === 'object' ? asset.id : asset)
                : []
            }
            
            // 添加额外调试日志
            console.log("提交的漏洞数据:", JSON.stringify(formData, null, 2))
            
            const response = await createVulnerability(formData)
            if (response.code === 200) {
              ElMessage.success('漏洞添加成功')
              router.push('/vulnerabilities')
            } else {
              ElMessage.error(response.message || '添加失败')
            }
          } catch (error) {
            console.error('添加漏洞失败:', error)
            
            // 显示更详细的错误信息
            let errorMessage = '添加漏洞失败'
            if (error.response) {
              errorMessage += `: ${error.response.status} ${error.response.statusText}`
              console.error('错误响应详情:', error.response.data)
            } else if (error.request) {
              errorMessage += ': 服务器未响应'
            } else {
              errorMessage += `: ${error.message}`
            }
            
            ElMessage.error(errorMessage)
          } finally {
            saving.value = false
          }
        }
      })
    }
    
    const goBack = () => {
      router.push('/vulnerabilities')
    }
    
    // 获取所有资产用于关联选择
    const fetchAssets = async () => {
      loadingAssets.value = true
      try {
        const response = await getAllAssets()
        if (response.code === 200) {
          // 处理不同的响应数据结构
          if (response.data && Array.isArray(response.data)) {
            // 直接使用数组结构
            assetList.value = response.data;
          } else if (response.data && response.data.items && Array.isArray(response.data.items)) {
            // 使用分页响应中的items数组
            assetList.value = response.data.items;
          } else {
            console.warn('获取资产列表成功，但数据格式不符合预期', response.data);
            assetList.value = [];
          }
          
          // 打印调试信息
          console.log('已加载资产列表，数量:', assetList.value.length);
        } else {
          console.warn('获取资产列表失败，响应码:', response.code);
          assetList.value = [];
        }
      } catch (error) {
        console.error('获取资产列表失败:', error)
        assetList.value = [];
      } finally {
        loadingAssets.value = false
      }
    }
    
    onMounted(() => {
      fetchAssets()
    })
    
    return {
      formRef,
      form,
      rules,
      saving,
      assetList,
      loadingAssets,
      handleSubmit,
      goBack
    }
  }
}
</script>

<style scoped>
.add-vuln-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cvss-value {
  margin-top: 5px;
  text-align: center;
  font-weight: bold;
}
</style> 